/**
 * Created by Administrator on 2017/6/17.
 */

let userDao = require('../mysql/userDao.js');
let bluedSDK = require('../util/bluedSDK.js');
let log = require('../util/log.js');
let create = require('./create.js');
let rpc = require('../util/rpc.js');

module.exports = blued;

function blued(token, expire, platform) {
    this._token = token;
    this._expire = expire;
    this._platform = platform;
    this._uid = null;
    this._name = null;
    this._avatar = null;
    this._cb = null;
}

blued.prototype.run = function (cb) {
    this._cb = cb;
    if (this._expire <= 0) {
        this.refresh();
    } else {
        this.self();
    }
};

blued.prototype.refresh = function () {
    //log.p('access_token:' + this._token + '过期，尝试更换');
    let _this = this;
    bluedSDK.refresh(this._token, function (result) {
        if (result.code != 200) {
            log.e('blued refresh error:' + result.code);
            _this._cb(null, {'error': 103, 'msg': 'accessToken过期，更新失败'});
            return false;
        }
        this._token = result.data[0].access_token;
        this._expire = result.data[0].expire;
        _this.self();
    });
};

blued.prototype.self = function () {
    //log.p('access_token:' + this._token + '开始拉取用户信息');
    let _this = this;
    bluedSDK.self(this._token, function (result) {
        if (result.code != 200) {
            log.e('blued self error:' + result.code);
            _this._cb(null, {'error': 104, 'msg': '拉取blued用户信息失败'});
            return false;
        }
        _this._uid = result.data[0].uid;
        _this._name = result.data[0].name;
        _this._avatar = result.data[0].avatar;
        let userModel = new userDao();
        userModel.inBluedId(_this._uid, function (err, res) {
            if (res == null) {
                _this.reg();
            } else {
                console.log(_this._avatar);
                let param = {};
                param.name = _this._name;
                param.avatar = _this._avatar;
                create.reToken(userModel, param, _this._cb);
            }
        });
        let param = {};
        param.uid = _this._uid;
        param.accessToken = _this._token;
        param.expire = _this._expire;
        param.platform = _this._platform;
        rpc.dc.send('setBlued',param);
    });
};

blued.prototype.reg = function () {
    let _this = this;
    create.blued(this._uid, this._name, this._avatar, function (err, res, token) {
        if (res == null) {
            _this._cb(null, {'error': 105, 'msg': '创建账号失败'});
            return false;
        }
        _this._cb(null, {'token': token});
    });
};